﻿using PlaneCleanEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using DbFactory;
using System.Net.Http;
using System.Net;
using PlaneClean.Models;
using System.Net.Http.Formatting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;

namespace PlaneClean.Filter
{
   
    /// <summary>
    /// 验证是否有访问此网站权限的过滤器 入 sign access_key timestemp等
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class AuthorizeFilter : AuthorizeAttribute
    {
        //public static void setCorsHeader(HttpResponse res, HttpRequest request)
        //{
        //    res.Headers.Add("Access-Control-Allow-Origin", request.Headers.GetValues("Origin").FirstOrDefault());
        //    res.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");//允许跨域的请求方式
        //    res.Headers.Add("Access-Control-Max-Age", "3600");//预检请求的间隔时间
        //    res.Headers.Add("Access-Control-Allow-Headers", string.Join(",", request.Headers.GetValues("Access-Control-Request-Headers")));
        //    //res.Headers.Add("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token,Access-Control-Allow-Headers");//允许跨域请求携带的请求头
        //    res.Headers.Add("Access-Control-Allow-Credentials", "true");//若要返回cookie、携带seesion等信息则将此项设置我true
        //}
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //string access_key = request.Params["access_key"];//不管是post请求还是get请求，都从地址栏获取key跟sign
            //string sign = request.Params["sign"];
            //校验IP
            var ip = HttpContext.Current.Request.UserHostAddress;
            //url = HttpContext.Current.Request.Headers.GetValues("Origin").FirstOrDefault();

            //setCorsHeader(HttpContext.Current.Response, HttpContext.Current.Request);

            List<string> ipStrList = dbFactory.Db.Queryable<t_write_ip>().Select(a => a.ip_address).ToList();
            if (ipStrList != null && ipStrList.Count > 0 && !ipStrList.Contains(ip))
            {
                actionContext.Response = new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new ObjectContent<BaseResponse>(
                          new BaseResponse() { result = "NG", reason = $"IP:{HttpContext.Current.Request.UserHostAddress}没有调用服务的权限" },
                          new JsonMediaTypeFormatter(),
                          "text/json"
                          )
                };
                return;
            }
            //var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;//获取传统context
            //HttpRequestBase request = content.Request;//定义传统request对象
            //string aaas = request["adfd"];//传统request获取querystring
            var requestContent = actionContext.Request.Content.ReadAsStringAsync();//读取post提交的json数据

            requestContent.Wait();//等待异步读取结束
            var inputJson = requestContent.Result;//请求json的数据
            if (string.IsNullOrEmpty(inputJson))
            {
                actionContext.Response = new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new ObjectContent<BaseResponse>(
                          new BaseResponse() { result = "NG", reason = "请传入Json格式请求数据" },
                          new JsonMediaTypeFormatter(),
                          "text/json"
                          )
                };
                return;
            }
            try
            {
                JObject json = JObject.Parse(inputJson);//json数据转换成json对象 json["token"]方式获取具体数据
                //if (json["body"] == null || json["body"].ToString() == "")
                //{
                //    actionContext.Response = new HttpResponseMessage()
                //    {
                //        StatusCode = HttpStatusCode.OK,
                //        Content = new ObjectContent<BaseResponse>(
                //              new BaseResponse() { result = "NG", reason = "请求body不能为空" },
                //              new JsonMediaTypeFormatter(),
                //              "text/json"
                //              )
                //    };
                //    return;
                //}
            }
            catch (Exception)
            {

                actionContext.Response = new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new ObjectContent<BaseResponse>(
                         new BaseResponse() { result = "NG", reason = "请传入Json格式请求数据" },
                         new JsonMediaTypeFormatter(),
                         "text/json"
                         )
                };
                return;
            }
           

            string ApiUrl = actionContext.Request.RequestUri.OriginalString;
            //base.OnAuthorization(actionContext);
        }
    }
}